package com.open.ui.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Space;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.open.ui.R;
import com.open.ui.skin.SkinManager;
import com.open.ui.widget.TVUIButton;
import com.open.ui.widget.TVUITextView;

import java.util.ArrayList;
import java.util.List;

/**
 * 构造 Dialog 对话框
 */
public abstract class TVUIDialogBuilder<T extends TVUIDialogBuilder> {

    private Context mContext;
    protected List<TVUIDialogButtonAction> mBtnActions = new ArrayList<>();
    protected String mTitle;
    protected Integer mHeight;
    protected Integer mWidth;
    protected Integer mSpace;

    protected Integer mTitleColorRes;
    protected Integer mBgColorRes;

    public TVUIDialogBuilder(Context context) {
        this.mContext = context.getApplicationContext();
    }

    /**
     * 设置整体布局背景颜色
     */
    public T setBackgroundColor(int res) {
        mBgColorRes = res;
        return (T) this;
    }

    /**
     * 设置整体布局高度
     */
    public T setHeight(int height) {
        this.mHeight = height;
        return (T) this;
    }

    /**
     * 设置整体布局宽度
     */
    public T setWidth(int width) {
        this.mWidth = width;
        return (T) this;
    }

    /**
     * 布局内的间距(上，下，左右)
     */
    public T setSpace(int padding) {
        this.mSpace = padding;
        return (T) this;
    }

    /**
     * 设置标题颜色
     */
    public T setTitleColor(int colorRes) {
        this.mTitleColorRes = colorRes;
        return (T) this;
    }

    public T setTitle(String title) {
        mTitle = title;
        return (T) this;
    }

    public T setTitle(int resId) {
        return setTitle(mContext.getResources().getString(resId));
    }

    public Context getContext() {
        return mContext;
    }

    /**
     * 添加对话框底部按钮
     * @param txt 按钮标题
     * @param cb 按钮回调
     * @return T
     */
    public T addButtonAction(String txt, TVUIDialogButtonAction.OnCallBackListener cb) {
        // 保存按钮信息
        mBtnActions.add(new TVUIDialogButtonAction()
                .text(txt)
                .onCallBack(cb));
        return (T) this;
    }

    public T addButtonAction(int txtResId, TVUIDialogButtonAction.OnCallBackListener cb) {
        return addButtonAction(mContext.getResources().getString(txtResId), cb);
    }

    public Dialog create() {
        return create(SkinManager.getInstance(mContext).getDialogSkinRes());
    }

    public Dialog create(int styleRes) {
        TVUIDialog dialog = new TVUIDialog(mContext, styleRes);
        Context dialogContext = dialog.getContext();
        //
        ConstraintLayout dialogView = new ConstraintLayout(dialogContext);
        View titleView = onCreateTitle(dialog);
        View contentLayout = onCreateContent(dialog);
        View buttonsLayout = onCreateButtonsLayout(dialog);
        // 设置相关ID，方便进行布局.
        checkAndSetId(dialogView, R.id.tvui_dialog_dialogView_id);
        checkAndSetId(titleView, R.id.tvui_dialog_title_id);
        checkAndSetId(contentLayout, R.id.tvui_dialog_content_id);
        checkAndSetId(buttonsLayout, R.id.tvui_dialog_buttons_layout_id);
        // 添加标题布局
        if (null != titleView) {
            ConstraintLayout.LayoutParams lp = onCreateTitleLayoutParams(dialogContext);
//            if (null != contentLayout) { // bottom 对齐 内容布局 top
//                lp.bottomToTop = R.id.tvui_dialog_content_id;
//            } else if (null != buttonsLayout) { // bottom 对齐 下部按钮布局 top
//                lp.bottomToTop = R.id.tvui_dialog_buttons_layout_id;
//            } else { // 对齐父布局
//                lp.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
//            }
            dialogView.addView(titleView, lp);
        }
        // 添加内容布局
        if (null != contentLayout) {
            ConstraintLayout.LayoutParams lp = onCreateContentLayoutParams(dialogContext);
            if (titleView != null) { // top对齐 标题布局 bottom
                lp.topToBottom = R.id.tvui_dialog_title_id;
//                lp.leftToLeft = R.id.tvui_dialog_title_id;
//                lp.rightToRight = R.id.tvui_dialog_title_id;
            } else { // 对齐父布局
                lp.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
            }

            if (buttonsLayout != null) { // bottom 对齐 下部按钮布局 top
                lp.bottomToTop = R.id.tvui_dialog_buttons_layout_id;
            } else { // 对齐父布局
                lp.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
            }

            dialogView.addView(contentLayout, lp);
        }
        // 添加底部按钮布局
        if (null != buttonsLayout) {
            ConstraintLayout.LayoutParams lp = onCreateButtonsLayoutLayoutParams(dialogContext);
            dialogView.addView(buttonsLayout, lp);
        }

        FrameLayout.LayoutParams dialogViewLayoutParams = onCreateDialogLayoutParams();
        // 初始化相关属性
        int width = SkinManager.getAttrDimen(dialogContext, R.attr.tvui_dialog_width);
        int height = SkinManager.getAttrDimen(dialogContext, R.attr.tvui_dialog_height);
        Drawable drawable = SkinManager.getAttrDrawable(dialogContext, R.attr.tvui_dialog_background);
        int space = SkinManager.getAttrDimen(dialogContext, R.attr.tvui_dialog_space);
        if (mBgColorRes != null) {
            dialogView.setBackgroundColor(mBgColorRes);
        } else {
            dialogView.setBackgroundDrawable(drawable);
        }
        dialogViewLayoutParams.width = mWidth != null ? mWidth : width;
        dialogViewLayoutParams.height = mHeight != null ? mHeight : height; // 按照设计师统一的 Dialog大小.如果有特殊的，可能只是高度变大，其它情况按照设计师高度.
        dialogViewLayoutParams.gravity = Gravity.CENTER;
        dialogView.setClipChildren(false);
        dialogView.setClipToPadding(false);
        if (mSpace != null) {
            space = mSpace;
        }
        dialogView.setPadding(space, space, space, space);
        //
        dialog.addContentView(dialogView, dialogViewLayoutParams);
        return dialog;
    }

    protected FrameLayout.LayoutParams onCreateDialogLayoutParams() {
        return new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    protected ConstraintLayout.LayoutParams onCreateTitleLayoutParams(Context context) {
        ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
        lp.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
        lp.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
        lp.verticalChainStyle = ConstraintLayout.LayoutParams.CHAIN_PACKED;
        return lp;
    }

    protected ConstraintLayout.LayoutParams onCreateContentLayoutParams(Context context) {
        ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
        lp.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
        lp.constrainedHeight = true;
        return lp;
    }

    protected ConstraintLayout.LayoutParams onCreateButtonsLayoutLayoutParams(@NonNull Context context) {
        ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
        lp.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
        lp.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
        lp.verticalChainStyle = ConstraintLayout.LayoutParams.CHAIN_PACKED;
        return lp;
    }

    public View onCreateTitle(TVUIDialog dialog) {
        TVUITextView tv = new TVUITextView(dialog.getContext());
        tv.setText(mTitle);
        int textSize = SkinManager.getAttrDimen(dialog.getContext(), R.attr.tvui_dialog_title_size);
        ColorStateList textColorList = SkinManager.getAttrColorStateList(dialog.getContext(),
                mTitleColorRes != null ? mTitleColorRes : R.attr.tvui_dialog_title_color);
        tv.setTextSize(textSize);
        tv.setTextColor(textColorList);
        tv.setGravity(Gravity.CENTER_HORIZONTAL);
        return tv;
    }

    /**
     * 中间的布局内容，可以进行重写，设置自己的内容
     * @param dialog
     * @return
     */
    protected abstract View onCreateContent(TVUIDialog dialog);

    /**
     * 创建下部按钮布局
     */
    public View onCreateButtonsLayout(TVUIDialog dialog) {
        final Context context = dialog.getContext();
        final LinearLayout layout = new LinearLayout(context);
        layout.setOrientation(mOrientation);
        if (mBtnActions.size() > 0) {
            TypedArray array = context.obtainStyledAttributes(
                    null, R.styleable.TVUIDialog, R.attr.TVUIDialogStyle, 0);
            int count = array.getIndexCount();
            int btnPadding = 54;
            int btnHeight = 80;
            int btnHSpace = 24; // 按钮之间的间距(从右边开始算)
            int btnVSpace = 24; // 按钮之间的间距(从右边开始算)

            for (int i = 0; i < count; i++) {
                int attr = array.getIndex(i);
                if (attr == R.styleable.TVUIDialog_tvui_dialog_button_height) {
                    btnHeight = (int) array.getDimension(attr, 0.0f);
                } else if (attr == R.styleable.TVUIDialog_tvui_dialog_button_lrpadding) {
                    btnPadding = array.getDimensionPixelSize(attr, 0);
                } else if (attr == R.styleable.TVUIDialog_tvui_dialog_button_hspace) {
                    btnHSpace = array.getDimensionPixelSize(attr, 0);
                } else if (attr == R.styleable.TVUIDialog_tvui_dialog_button_vspace) {
                    btnVSpace = array.getDimensionPixelSize(attr, 0);
                }
            }
            array.recycle();
            // 添加底部的按钮
            int size = mBtnActions.size();
            for (int i = 0; i < size; i++) {
                // 最左边占位
                if (i == 0) {
                    layout.addView(createActionContainerSpace(context));
                }
                // 按钮
                TVUIDialogButtonAction btnAction = mBtnActions.get(i);
                TVUIButton btn = btnAction.onCreateButton(dialog);
                btn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        float scale = hasFocus ? 1.1f : 1.0f;
                        v.animate().scaleX(scale).scaleY(scale).setDuration(300).start();
                    }
                });
                btn.setPadding(btnPadding, 0, btnPadding, 0);
//                btn.setTextSize(56);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, btnHeight);
                if (i < size - 1) {
                    if (mOrientation == LinearLayout.VERTICAL) {
                        lp.bottomMargin = btnVSpace;
                    } else {
                        lp.rightMargin = btnHSpace;
                    }
                }

                // 设置
                if (mOrientation == LinearLayout.VERTICAL) {
                    lp.gravity = Gravity.CENTER_HORIZONTAL;
                } else {
                    lp.gravity = Gravity.CENTER_VERTICAL;
                }

                layout.addView(btn, lp);
                // 最右边占位
                if (i == size - 1) {
                    layout.addView(createActionContainerSpace(context));
                }
                // 设置 背景/文字 颜色
                ColorStateList textColorList = SkinManager.getAttrColorStateList(dialog.getContext(), R.attr.tvui_dialog_button_textColor);
                btn.setTextColor(textColorList);
                ColorStateList bgColorList = SkinManager.getAttrColorStateList(dialog.getContext(), R.attr.tvui_dialog_button_backgroundColor);
                btn.setBackgroundColor(bgColorList);
            }
        }
        //
        layout.setClipChildren(false);
        layout.setClipToPadding(false);
        return layout;
    }

    int mOrientation = LinearLayout.HORIZONTAL;

    public T setButtonsOrientation(int orientation) {
        this.mOrientation = orientation;
        return (T)this;
    }

    /**
     * 用来占位 按钮布局 两边
     */
    private View createActionContainerSpace(Context context) {
        Space space = new Space(context);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 0);
        lp.weight = 1;
        space.setLayoutParams(lp);
        return space;
    }

    /**
     * 用于设置相关ID，方便布局
     */
    private void checkAndSetId(View view, int id) {
        if (view != null && view.getId() == View.NO_ID) {
            view.setId(id);
        }
    }

    public static void testTVUIDialog(final Context context) {
        new TVUIDialog.MessageDialogBuilder(context)
                .setTitle("标题测试")
                .setMessage("清除配对后，您的遥控器需要重新进行配对")
                .addButtonAction("确定", new TVUIDialogButtonAction.OnCallBackListener() {
                    @Override
                    public void onCallBack(TVUIDialog dialog, View view) {
                        dialog.dismiss();
                    }
                })
                .addButtonAction("取消配对", new TVUIDialogButtonAction.OnCallBackListener() {
                    @Override
                    public void onCallBack(TVUIDialog dialog, View view) {
                        dialog.dismiss();
                    }
                }).create().show();
    }

}
